package com.lmt_28;

import com.sun.security.ntlm.Server;

import java.io.*;
import java.net.Socket;

public class ServerThread extends Thread{
    private Socket socket;
    public ServerThread(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        super.run();
        try {
            InputStream in= socket.getInputStream();
            DataInputStream dis = new DataInputStream(in);
            while (true){
               try {
                   String s = dis.readUTF();
//                   System.out.println(s);
                   sendToAll(s);
               }catch (Exception e){
                   // 接受不到数据
                   System.out.println(socket.getRemoteSocketAddress() + "离线了");
                   TCPServer.onlineSocket.remove(socket);
                   in.close();
                   socket.close();
                   break;
               }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void sendToAll(String msg) throws Exception {
        // 发送给全部在线的客户端
        for (Socket sock : TCPServer.onlineSocket) {
            OutputStream os = sock.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            dos.writeUTF(msg);
            dos.flush();
        }
    }
}
